package com.jollychic.db;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.jollychic.db.function.RSFunction;
import com.jollychic.db.utils.DBUtils;

/**
 * 数据库操作
 * 
 * @author zhangyong
 *
 * @param <T>
 */
public class MySQL<T> implements DB<T> {

	@Override
	public T queryOne(String sqlStr, Object[] params, Class<T> cls) {
		PreparedStatement ps = DBUtils.setParams(DBUtils.getPS(sqlStr), params);
		ResultSet rs = null;
		try {
			rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("execute SQL has an error");
		}
//        解析结果集
		T t = DBUtils.getRSet2One(rs, cls);
		return t;
	}

	@Override
	public List<T> queryList(String sqlStr, Object[] params, Class<T> cls) {
		PreparedStatement ps = DBUtils.setParams(DBUtils.getPS(sqlStr), params);
		ResultSet rs = null;
		try {
			rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("execute SQL has an error");
		}
//          解析结果集
		List<T> lst = DBUtils.getRSet2List(rs, cls);
		DBUtils.close(ps, rs);
		return lst;
	}

	@Override
	public int update(String sqlStr, Object[] params) {
		PreparedStatement ps = DBUtils.setParams(DBUtils.getPS(sqlStr), params);
		int result = -1;
		try {
			result = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		DBUtils.close(ps);
		return result;
	}

	@Override
	public T query(String sqlStr, Object[] params, RSFunction<T> fun) {
		PreparedStatement ps = DBUtils.setParams(DBUtils.getPS(sqlStr), params);
		ResultSet rs = null;
		try {
			rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("executor SQL  has an error");
		}
		T t = fun.wrapped(rs);
		DBUtils.close(ps,rs);
		return t;
	}

}
